﻿using MiniExcelLibs;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebDataGet.Models;
using WebDataGet.Utils;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace WebDataGet.Services
{
    public class ConfigService
    {
        private NlogService NlogService { get; set; }

        public ConfigSetting Setting { get; set; }

        public List<ExcelData> ExcelDatas { get; set; }

        public ConfigService() { }
        public ConfigService(NlogService nlogService)
        {
            NlogService = nlogService;
            Init();

        }


        public void Init()
        {
            ReadConfig();
            ReadExcelData();
        }


        private void ReadConfig()
        {
            NlogService.Debug("正在读取配置文件");
            var config = new ConfigSetting();
            var xmlAutoHelper = new MyXmlConfigAutoHelper<ConfigSetting>("Assest\\MyConfig.xml", config);
            xmlAutoHelper.AutoInit();

            NlogService.Info("配置文件读取成功!");
            NlogService.Debug(JsonConvert.SerializeObject(config));
            Setting = config;

        }

        private void ReadExcelData()
        {
            string filePath = "Assest\\Data.xlsx";
            var isExist = File.Exists(filePath);
            if (isExist)
            {
                NlogService.Debug($"配置文件[{filePath}]存在，读取文件");
                ExcelDatas = MiniExcel.Query<ExcelData>(filePath).ToList();
                NlogService.Info($"配置文件[{filePath}]读取成功！");
            }
            else
            {
                NlogService.Warning($"不存在配置文件[{filePath}]，生成默认配置文件");

                ExcelDatas = new List<ExcelData> {
                        new ExcelData(){Id = 1}
                    };
                MiniExcel.SaveAs(filePath, ExcelDatas);
                NlogService.Info("默认配置文件生成成功！");

            }

        }

    }
}
